package buildtools;

import component.Ball;
import component.ComponentFactory;
import component.Status;
import component.Structure;
import component.Tube;

public class BallAdder {

	private Tube tube;
	
	private Ball[] ballList = new Ball[2];
	
	private Connector connector;

	private Structure structure;

	private ComponentFactory factory;

	public BallAdder(Structure structure, ComponentFactory factory, Connector connector) {
		this.structure = structure;
		this.factory = factory;
		this.connector = connector;
	}
	
	public void addToTube(Tube tube) {
		this.tube = tube;
		
		if (hasFreeSlots(tube))
			createBallList();
	}
	
	public boolean selectBall(Ball ball) {
		boolean valid = false;

		if (ballList[0] != null && ballList[0] == ball)
			valid = true;
		
		if (ballList[1] != null && ballList[1] == ball)
			valid = true;

		if (!valid) return false;
		
		ball.setStatus(Status.NORMAL);
			
		connector.connectToNearbyTubes(ball);
		structure.transferToPermanent(ball);
	
		clearData();
		
		return valid;
	}

	public boolean isActive() {
		return tube != null ? true : false;
	}
	
	public void clearData() {
		ballList[0] = null;
		ballList[1] = null;
		
		structure.clearTemporaryComponents();
		
		tube = null;
	}
	
	private void createBallList() {
		if (ballList[0] != null) 
			structure.addTemporaryComponent(ballList[0]);
			
		if (ballList[1] != null) 
			structure.addTemporaryComponent(ballList[1]);
	}
	
	public boolean hasFreeSlots(Tube tube) {
		Ball ball = factory.createBall(tube.getPos());
		ball.setStatus(Status.PLACEMENT | Status.TRANSPARENT);
		
		boolean freeSlots = false;
		if (ball.isValidPosition()) {
			ballList[0] = ball;
			freeSlots = true;
		}
		else
			ballList[0] = null;

		ball = factory.createBall(tube.getSecondaryPosition());
		ball.setStatus(Status.PLACEMENT | Status.TRANSPARENT);
		
		if (ball.isValidPosition()) {
			ballList[1] = ball;
			freeSlots = true;
		}
		else
			ballList[1] = null;
	
		return freeSlots;
	}
}
